package com.springbase.demo.config;


import io.swagger.annotations.ApiOperation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Author: flyFan
 * @Date: 2021/9/15 10:34
 * @Version: 1.0
 */
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enabled", havingValue = "true")
public class SwaggerConfig  extends WebMvcConfigurationSupport {
	
	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 注册 swagger/doc 可视化操作界面
		registry.addResourceHandler("swagger-ui.html")
				.addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("doc.html")
				.addResourceLocations("classpath:/META-INF/resources/");

		registry.addResourceHandler("/webjars/**")
				.addResourceLocations("classpath:/META-INF/resources/webjars/");
	}
	
	/**
	 * 可创建多个 Docket 模块
	 * @return
	 */
	@Bean
	public Docket buildDocket1() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(buildApiInf("模块功能1","模块功能API"))
				.select()
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
				.apis(RequestHandlerSelectors.basePackage("com.springbase.demo.controller.*"))
				.paths(PathSelectors.any())
				.build()
				.groupName("模块功能API_1");
	}
	
	@Bean
	public Docket buildDocket2() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(buildApiInf("模块功能2","模块功能API"))
				.select()
				.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
				.apis(RequestHandlerSelectors.basePackage("com.springbase.demo.controller.*"))
				.paths(PathSelectors.any())
				.build()
				.groupName("模块功能API_2");
	}
	
	private ApiInfo buildApiInf(String title, String desc) {
		return new ApiInfoBuilder()
				.title(title)
				.description(desc)
				.contact(new Contact("flyFan", "https://localhost:8080", "flyFan@163.com"))
				.version("1.0")
				.build();
	}
}
